package com.sugon.api;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.LoginUser;
import com.sugon.entity.*;
import com.sugon.entity.dto.ConfirmStockOutParam;
import com.sugon.modules.mold.consts.MoldSpStockState;
import com.sugon.modules.sys.consts.SysDeptConst;
import com.sugon.service.ModuleSpDeptStockService;
import com.sugon.service.ModuleSpService;
import com.sugon.service.ModuleSpStockService;
import com.sugon.util.ApiBaseAction;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 模具型芯备件接口
 *
 * @author YuXD
 * @since 2022-03-05
 */
@Api(tags = "模具型芯接口API")
@RestController
@RequestMapping("/api/v1/moldSp")
public class MoldSpApiController extends ApiBaseAction {

    @Autowired
    private ModuleSpService moduleSpService;
    @Autowired
    private ModuleSpStockService moduleSpStockService;
    @Resource
    private ModuleSpDeptStockService moldSpDeptStockService;

    /**
     * 模具型芯查询API
     *
     * @param params
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具型芯查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "模具型芯名称", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "form", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "form", dataType = "int", required = true)
    })
    @PostMapping
    public ApiResult<PageUtils> querySpareParts(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        //查询列表数据
        Query query = new Query(params);
        List<ModuleSpEntity> moldSpList = moduleSpService.queryList(query);
        int total = moduleSpService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(moldSpList, total, query.getLimit(), query.getPage());
        return apiResult.success(pageUtil);
    }

    @AuthCheck
    @ApiOperation(value = "型芯车间库存统计查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sparePartsName", value = "模具型芯名称", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "form", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "form", dataType = "int", required = true)
    })
    @PostMapping("/deptStock")
    public ApiResult<PageUtils> querySparePartsDeptStock(@ApiIgnore @RequestParam Map<String, Object> params, @ApiIgnore @LoginUser SysUserEntity loginUser) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        // 非制造处用户只可以查看自己的部门统计
        if (StrUtil.isNotEmpty(loginUser.getWorkShopId()) && !StrUtil.equals(SysDeptConst.ZZC_CODE, loginUser.getWorkShopId())) {
            params.put("filterSql", StrUtil.format(" AND MSDS.WORKSHOP = '{}'", loginUser.getDeptCode()));
        }
        //查询列表数据
        Query query = new Query(params);
        List<ModuleSpDeptStockEntity> wkStockList = moldSpDeptStockService.queryList(query);
        int total = moldSpDeptStockService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(wkStockList, total, query.getLimit(), query.getPage());
        return apiResult.success(pageUtil);
    }

    @AuthCheck
    @ApiOperation(value = "车间型芯库存明细查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moldSpId", value = "模具型芯ID", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "storeId", value = "型芯所在仓库ID", paramType = "form", dataType = "int"),
            @ApiImplicitParam(name = "sparePartsName", value = "型芯名称", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "uniqueBarCode", value = "型芯条码代码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "batchMonth", value = "批次月份", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "库存状态,0: '待入库', 1: '在库', 2: '已出库', 3: '扫码出库中'", paramType = "form", dataType = "String", allowableValues = "0,1,2,3"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "form", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "form", dataType = "int", required = true)
    })
    @PostMapping("/stock")
    public ApiResult<PageUtils> querySparePartsStock(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        //查询列表数据
        Query query = new Query(params);
        List<ModuleSpStockEntity> moduleSpStockList = moduleSpStockService.queryList(query);
        int total = moduleSpStockService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(moduleSpStockList, total, query.getLimit(), query.getPage());
        return apiResult.success(pageUtil);
    }

    /**
     * 模具型芯查询API
     *
     * @param moldSpId
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具型芯查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moldSpId", value = "模具型芯ID", paramType = "path", dataType = "String", required = true),
    })
    @PostMapping("/info/{moldSpId}")
    public ApiResult<ModuleSpEntity> info(@PathVariable("moldSpId") String moldSpId) {
        ApiResult<ModuleSpEntity> apiResult = new ApiResult<>();
        return apiResult.success(moduleSpService.queryObject(moldSpId));
    }

    @AuthCheck
    @ApiOperation(value = "型芯待出库API")
    @ApiImplicitParam(name = "uniqueCode", value = "模具型芯条码", paramType = "query", dataType = "String", required = true)
    @PostMapping("/scanStockOut")
    public ApiResult<String> scanStockIn(@RequestParam String uniqueCode) {
        ApiResult<String> apiResult = new ApiResult<>();
        ModuleSpStockEntity moduleSpStockInDB = moduleSpStockService.queryListByUniqueCode(uniqueCode);
        if (moduleSpStockInDB == null) {
            return apiResult.failMsg("无法匹配，请确认是否已入库！");
        }
        // 校验出库状态
        Integer moldSpStockState = moduleSpStockInDB.getState();
        if (MoldSpStockState.ING.equals(moldSpStockState)) {
            return apiResult.failMsg("当前型芯尚未入库完毕，请确认！");
        } else if (MoldSpStockState.USED.equals(moldSpStockState)) {
            return apiResult.failMsg("当前型芯已使用，请勿重复扫码！");
        } else if (MoldSpStockState.LOCKING.equals(moldSpStockState)) {
            return apiResult.failMsg("当前型芯已扫码出库中，请勿重复扫码！");
        }
        moduleSpStockInDB.setState(MoldSpStockState.LOCKING);
        return moduleSpStockService.update(moduleSpStockInDB) > 0 ? apiResult.success() : apiResult.failMsg("扫码出库失败，请稍后重试！");
    }

    @AuthCheck
    @ApiOperation(value = "根据型芯条码获取型芯详情API")
    @ApiImplicitParam(name = "uniqueCode", value = "模具型芯条码", paramType = "query", dataType = "String", required = true)
    @PostMapping("/loadByUniqueCode")
    public ApiResult<ModuleSpStockEntity> load(@RequestParam String uniqueCode) {
        ApiResult<ModuleSpStockEntity> apiResult = new ApiResult<>();
        ModuleSpStockEntity moduleSpStockInDB = moduleSpStockService.queryListByUniqueCode(uniqueCode);
        if (moduleSpStockInDB == null) {
            return apiResult.failMsg("无法匹配，请确认是否已入库！");
        }
        return apiResult.success(moduleSpStockInDB);
    }

    @AuthCheck
    @ApiOperation(value = "查看我的待出库型芯列表API")
    @PostMapping("/listMyScan")
    public ApiResult<List<ModuleSpStockEntity>> listMyScan(@ApiIgnore @LoginUser SysUserEntity loginUser) {
        ApiResult<List<ModuleSpStockEntity>> apiResult = new ApiResult<>();
        Map<String, Object> param = MapUtil.newHashMap();
        param.put("modifyUser", loginUser.getUserId());
        param.put("state", MoldSpStockState.LOCKING);
        return apiResult.success(moduleSpStockService.queryList(param));
    }

    @AuthCheck
    @ApiOperation(value = "确认出库API")
    @PostMapping("/confirmStockOut")
    @ResponseBody
    public ApiResult<String> confirmStockOut(@Validated @RequestBody ConfirmStockOutParam confirmStockOutParam, BindingResult bindingResult, @ApiIgnore @LoginUser SysUserEntity loginUser) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 获取登录用户所在车间
        String currentWorkshop = loginUser.getWorkShopId();
        if (StrUtil.isEmpty(currentWorkshop)) {
            return apiResult.failMsg("登录用户不属于任何车间，不能执行该操作");
        }
        return moduleSpStockService.confirmStockOut(ArrayUtil.toArray(confirmStockOutParam.getIds(), String.class)) ? apiResult.success() : apiResult.failMsg("扫码出库失败，请稍后重试！");
    }

    @AuthCheck
    @ApiOperation(value = "取消出库API")
    @ApiImplicitParam(name = "id", value = "模具型芯库存ID", paramType = "query", dataType = "String", required = true)
    @PostMapping("/cancelStockOut")
    public ApiResult<String> cancelStockOut(String id) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 校验模具型芯库存是否存在
        ModuleSpStockEntity moldSpStock = moduleSpStockService.queryObject(id);
        if (moldSpStock == null) {
            return apiResult.failMsg("模具型芯库存记录不存在！");
        }
        if (!MoldSpStockState.LOCKING.equals(moldSpStock.getState())) {
            return apiResult.failMsg("只可以取消待出库的记录！");
        }
        moldSpStock.setState(MoldSpStockState.ED);
        return moduleSpStockService.update(moldSpStock) > 0 ? apiResult.success("取消成功！") : apiResult.failMsg("取消失败，请稍后重试！");
    }

}




